package com.smartcampusbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.smartcampusbackend.mapper.CommunityPostMapper;
import com.smartcampusbackend.mapper.PostCommentMapper;
import com.smartcampusbackend.mapper.LikeRecordMapper;
import com.smartcampusbackend.mapper.UserMapper;
import com.smartcampusbackend.mapper.InterestCommunityMapper;
import com.smartcampusbackend.model.CommunityPost;
import com.smartcampusbackend.model.PostComment;
import com.smartcampusbackend.model.LikeRecord;
import com.smartcampusbackend.model.InterestCommunity;
import com.smartcampusbackend.model.User;
import com.smartcampusbackend.service.CommunityPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CommunityPostServiceImpl implements CommunityPostService {

    @Autowired
    private CommunityPostMapper postMapper;
    
    @Autowired
    private PostCommentMapper commentMapper;
    

    
    @Autowired
    private LikeRecordMapper likeRecordMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private InterestCommunityMapper communityMapper;

    @Override
    @Transactional
    public CommunityPost createPost(CommunityPost post, Integer authorId) {
        // 获取用户信息
        User author = userMapper.selectById(authorId);
        if (author == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查realName是否为空
        if (author.getRealName() == null || author.getRealName().trim().isEmpty()) {
            throw new RuntimeException("用户真实姓名不能为空，请完善个人信息");
        }
        
        // 设置帖子信息
        post.setAuthorId(authorId);
        post.setAuthorName(author.getRealName().trim());
        post.setLikeCount(0);
        post.setCommentCount(0);
        post.setViewCount(0);
        post.setStatus(1);
        post.setCreateTime(LocalDateTime.now());
        post.setUpdateTime(LocalDateTime.now());
        
        // 保存帖子
        postMapper.insert(post);
        
        // 更新社群的帖子数量
        updateCommunityPostCount(post.getCommunityId());
        
        return post;
    }

    @Override
    @Transactional
    public boolean deletePost(Integer postId, Integer userId, boolean isAdmin) {
        CommunityPost post = postMapper.selectById(postId);
        if (post == null) throw new RuntimeException("帖子不存在");
        if (!isAdmin && !post.getAuthorId().equals(userId)) {
            throw new RuntimeException("无权删除该帖子");
        }
        // 删除帖子及相关评论、点赞等
        postMapper.deleteById(postId);
        // TODO: 如有评论、点赞等，需一并删除
        return true;
    }

    @Override
    public List<CommunityPost> getCommunityPosts(Integer communityId) {
        return postMapper.findByCommunityIdOrderByCreateTimeDesc(communityId);
    }

    @Override
    public CommunityPost getPostDetail(Integer postId) {
        CommunityPost post = postMapper.selectById(postId);
        if (post != null) {
            // 增加浏览次数
            post.setViewCount(post.getViewCount() + 1);
            postMapper.updateViewCount(postId, post.getViewCount());
        }
        return post;
    }

    @Override
    @Transactional
    public boolean togglePostLike(Integer postId, Integer userId) {
        CommunityPost post = postMapper.selectById(postId);
        if (post == null) {
            throw new RuntimeException("帖子不存在");
        }
        
        // 检查是否已点赞
        QueryWrapper<LikeRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
               .eq("target_type", "POST")
               .eq("target_id", postId);
        
        LikeRecord existingLike = likeRecordMapper.selectOne(wrapper);
        
        if (existingLike != null) {
            // 取消点赞
            likeRecordMapper.deleteById(existingLike.getId());
            post.setLikeCount(post.getLikeCount() - 1);
            postMapper.updateLikeCount(postId, post.getLikeCount());
            return false;
        } else {
            // 添加点赞
            LikeRecord likeRecord = new LikeRecord();
            likeRecord.setUserId(userId);
            likeRecord.setTargetType("POST");
            likeRecord.setTargetId(postId);
            likeRecord.setCreateTime(LocalDateTime.now());
            likeRecordMapper.insert(likeRecord);
            
            post.setLikeCount(post.getLikeCount() + 1);
            postMapper.updateLikeCount(postId, post.getLikeCount());
            return true;
        }
    }

    @Override
    @Transactional
    public PostComment createComment(PostComment comment, Integer authorId) {
        // 获取用户信息
        User author = userMapper.selectById(authorId);
        if (author == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查realName是否为空
        if (author.getRealName() == null || author.getRealName().trim().isEmpty()) {
            throw new RuntimeException("用户真实姓名不能为空，请完善个人信息");
        }
        
        // 设置评论信息
        comment.setAuthorId(authorId);
        comment.setAuthorName(author.getRealName().trim());
        comment.setLikeCount(0);
        comment.setStatus(1);
        comment.setCreateTime(LocalDateTime.now());
        
        // 保存评论
        commentMapper.insert(comment);
        
        // 更新帖子的评论数量
        CommunityPost post = postMapper.selectById(comment.getPostId());
        if (post != null) {
            post.setCommentCount(post.getCommentCount() + 1);
            postMapper.updateCommentCount(comment.getPostId(), post.getCommentCount());
        }
        
        return comment;
    }

    @Override
    @Transactional
    public boolean deleteComment(Integer commentId, Integer userId) {
        PostComment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            throw new RuntimeException("评论不存在");
        }
        
        // 检查权限：只有评论者或帖子作者可以删除
        if (!comment.getAuthorId().equals(userId)) {
            CommunityPost post = postMapper.selectById(comment.getPostId());
            if (post == null || !post.getAuthorId().equals(userId)) {
                throw new RuntimeException("没有权限删除此评论");
            }
        }
        
        // 删除评论
        commentMapper.deleteById(commentId);
        
        // 更新帖子的评论数量
        CommunityPost post = postMapper.selectById(comment.getPostId());
        if (post != null) {
            post.setCommentCount(post.getCommentCount() - 1);
            postMapper.updateCommentCount(comment.getPostId(), post.getCommentCount());
        }
        
        return true;
    }

    @Override
    public List<PostComment> getPostComments(Integer postId) {
        return commentMapper.findByPostIdOrderByCreateTimeDesc(postId);
    }

    @Override
    @Transactional
    public boolean toggleCommentLike(Integer commentId, Integer userId) {
        PostComment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            throw new RuntimeException("评论不存在");
        }
        
        // 检查是否已点赞
        QueryWrapper<LikeRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
               .eq("target_type", "COMMENT")
               .eq("target_id", commentId);
        
        LikeRecord existingLike = likeRecordMapper.selectOne(wrapper);
        
        if (existingLike != null) {
            // 取消点赞
            likeRecordMapper.deleteById(existingLike.getId());
            comment.setLikeCount(comment.getLikeCount() - 1);
            commentMapper.updateLikeCount(commentId, comment.getLikeCount());
            return false;
        } else {
            // 添加点赞
            LikeRecord likeRecord = new LikeRecord();
            likeRecord.setUserId(userId);
            likeRecord.setTargetType("COMMENT");
            likeRecord.setTargetId(commentId);
            likeRecord.setCreateTime(LocalDateTime.now());
            likeRecordMapper.insert(likeRecord);
            
            comment.setLikeCount(comment.getLikeCount() + 1);
            commentMapper.updateLikeCount(commentId, comment.getLikeCount());
            return true;
        }
    }


    
    // 更新社群的帖子数量
    private void updateCommunityPostCount(Integer communityId) {
        int postCount = postMapper.countByCommunityId(communityId);
        communityMapper.updatePostCount(communityId, postCount);
    }
} 